package servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import domain.Collection;
import domain.Product;
import domain.User;
import service.Factory.ServiceFactory;

/**
 * Servlet implementation class ProductDetail
 */
@WebServlet("/ProductDetailServlet")
public class ProductDetailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProductDetailServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("_user");
		String id = request.getParameter("id");
		
		try {
			Product product = ServiceFactory.getProductServiceInstance().findProductById(id);
			
			if (user != null) {
				Collection collection = ServiceFactory.getCollectionServiceInstance().findCollectionById(id, user.getId());
				request.setAttribute("collected", collection.getProduct() != null);
				request.setAttribute("collection", collection);
			}
			
			request.setAttribute("product", product);
			request.getRequestDispatcher("/client/ProductDetail.jsp").forward(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendRedirect(request.getContextPath()+ "/AllProductServlet");
		}
	}

}
